package com.andy.module.network

import android.os.Build
import com.andy.module.constant.AppConstant
import com.andy.module.constant.AppKey
import com.blankj.utilcode.util.DeviceUtils
import com.blankj.utilcode.util.SPUtils
import com.blankj.utilcode.util.Utils
import okhttp3.*
import java.util.*

/**
 * 作者　: hegaojian
 * 时间　: 2021/6/9
 * 描述　:
 */
open class HeadInterceptor : Interceptor {

    @Throws(java.io.IOException::class)
    override fun intercept(chain: Interceptor.Chain): Response {
        var request = chain.request()
        val requestBuilder = request.newBuilder()
        handlerHeaderParams(requestBuilder)
        request = requestBuilder.build()
        val paramsMap = HashMap<String, Any>() //这里是添加的body数据
        //因为是post请求
        if (paramsMap.size > 0) {
            if (request.body is FormBody) {
                val newFormBodyBuilder = FormBody.Builder()
                val oldFormBody = request.body as FormBody?
                val paramSize = oldFormBody!!.size
                if (paramSize > 0) {
                    for (i in 0 until paramSize) {
                        newFormBodyBuilder.add(oldFormBody!!.name(i), oldFormBody!!.value(i))
                    }
                }
                val iterator: Iterator<*> = paramsMap.entries.iterator()
                while (iterator.hasNext()) {
                    val entry = iterator.next() as Map.Entry<*, *>
                    newFormBodyBuilder.add(entry.key as String, entry.value as String)
                }
                requestBuilder.post(newFormBodyBuilder.build())
                request = requestBuilder.build()
            } else if (request.body is MultipartBody) {
                val multipartBuilder = MultipartBody.Builder().setType(MultipartBody.FORM)
                val iterator: Iterator<*> = paramsMap.entries.iterator()
                while (iterator.hasNext()) {
                    val entry = iterator.next() as Map.Entry<*, *>
                    multipartBuilder.addFormDataPart(entry.key as String, entry.value as String)
                }
                val oldParts = (request.body as MultipartBody?)!!.parts
                if (oldParts.isNotEmpty()) {
                    for (part in oldParts) {
                        multipartBuilder.addPart(part)
                    }
                }
                requestBuilder.post(multipartBuilder.build())
                request = requestBuilder.build()
            }
        }
        return chain.proceed(request)
    }

    open fun handlerHeaderParams(requestBuilder: Request.Builder) {
        val userAgent: String = getUserAgent()
        requestBuilder.addHeader("User-Agent", userAgent)
        val token: String = SPUtils.getInstance().getString(AppKey.TOKEN)
        //设备id
        requestBuilder.addHeader("_Device-Id_", DeviceUtils.getUniqueDeviceId())
        requestBuilder.addHeader("_Device-Type_", "Android") //平台
        requestBuilder.addHeader("_App-Version_", AppConstant.VERSION_NAME) //版本

        requestBuilder.addHeader("_Sys-Version_", "" + Build.VERSION.SDK_INT) //设备操作系统版本

        requestBuilder.addHeader("_Token_", token)
        requestBuilder.addHeader("_Device-Brand_", Build.BRAND)
        requestBuilder.addHeader("_Device-Model_", Build.MODEL)
        requestBuilder.addHeader("region", "online") //在线

        requestBuilder.addHeader("_Terminal-Type_", "Manage") //版本区分

        val mLocale: Locale = Utils.getApp().resources.configuration.locale
        val language = mLocale.language
        requestBuilder.addHeader("Accept-Language", "" + language) //在线
    }

    private fun getUserAgent(): String {
        var userAgent = ""
        val sb = StringBuffer()
        userAgent = System.getProperty("http.agent") //Dalvik/2.1.0 (Linux; U; Android 6.0.1; vivo X9L Build/MMB29M)
        var i = 0
        val length = userAgent.length
        while (i < length) {
            val c = userAgent[i]
            if (c <= '\u001f' || c >= '\u007f') {
                sb.append(String.format("\\u%04x", c.toInt()))
            } else {
                sb.append(c)
            }
            i++
        }
        return sb.toString()
    }

}